<template>
  <div class="dilution-calculator">
    <h2>果汁稀释计算器</h2>
    
    <!-- 水果选择和重量输入 -->
    <div class="input-section">
      <div class="input-group">
        <label>选择水果:</label>
        <select v-model="selectedFruit">
          <option value="">请选择水果</option>
          <option v-for="(data, fruit) in fruitYieldData" :key="fruit" :value="fruit">
            {{ fruit }}
          </option>
        </select>
      </div>

      <div class="input-group">
        <label>水果重量:</label>
        <div class="input-with-unit">
          <input type="number" v-model="fruitWeight" min="0" max="100000" step="0.1">
          <select v-model="weightUnit">
            <option value="g">克 (g)</option>
            <option value="kg">千克 (kg)</option>
            <option value="lb">磅 (lb)</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 糖度和体积输入 -->
    <div class="input-section">
      <div class="input-group">
        <label>原始糖度 (°Brix):</label>
        <input type="number" v-model="originalBrix" min="0" max="80" step="0.1">
      </div>

      <div class="input-group">
        <label>目标糖度 (°Brix):</label>
        <input type="number" v-model="targetBrix" min="0" max="80" step="0.1">
      </div>

      <div class="input-group">
        <label>果汁体积:</label>
        <div class="input-with-unit">
          <input type="number" v-model="juiceVolume" min="0" max="100000" step="0.1">
          <select v-model="volumeUnit">
            <option value="mL">毫升 (mL)</option>
            <option value="L">升 (L)</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 计算结果显示 -->
    <div v-if="selectedFruitData" class="results-section">
      <h3>水果信息</h3>
      <div class="fruit-info">
        <p>典型糖度范围: {{ selectedFruitData.brixRange }} °Brix</p>
        <p>预计出汁率: {{ (selectedFruitData.yieldFactor * 100).toFixed(0) }}%</p>
        <p v-if="selectedFruitData.note">注意: {{ selectedFruitData.note }}</p>
        <p v-if="estimatedJuiceVolume">预计果汁产量: {{ estimatedJuiceVolume.toFixed(1) }} {{ volumeUnit }}</p>
      </div>
    </div>

    <div v-if="canCalculate" class="results-section">
      <h3>稀释计算结果</h3>
      <div class="calculation-results">
        <p>需要添加的水: {{ waterToAdd.toFixed(1) }} {{ volumeUnit }}</p>
        <p>稀释后总体积: {{ totalVolume.toFixed(1) }} {{ volumeUnit }}</p>
        <p>稀释比例 (水:果汁): {{ dilutionRatio }}:1</p>
        <p>最终糖分含量: {{ sugarContent.toFixed(1) }} g/L</p>
      </div>
    </div>

    <!-- 参考信息 -->
    <div class="reference-section">
      <h3>常见水果糖度参考</h3>
      <div class="fruit-reference-grid">
        <div v-for="(data, fruit) in fruitYieldData" :key="fruit" class="fruit-reference-item">
          <span class="fruit-name">{{ fruit }}</span>
          <span class="fruit-brix">{{ data.brixRange }} °Bx</span>
          <span class="fruit-yield">{{ (data.yieldFactor * 100).toFixed(0) }}%</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { BeakerIcon } from '@heroicons/vue/24/outline'

// 水果糖度数据
const fruitBrixData = {
  '苹果': { min: 12, max: 14, note: '品种差异' },
  '葡萄': { min: 16, max: 18, note: '品种重要' },
  '橙子': { min: 11, max: 13, note: '成熟度影响' },
  '西瓜': { min: 8, max: 10, note: '熟透更甜' },
  '草莓': { min: 8, max: 11, note: '季节影响' },
  '蓝莓': { min: 10, max: 12, note: '' },
  '樱桃': { min: 14, max: 16, note: '甜度高' },
  '桃子': { min: 8, max: 12, note: '成熟度影响' },
  '李子': { min: 12, max: 15, note: '品种差异大' },
  '杏子': { min: 10, max: 13, note: '' },
  '树莓': { min: 9, max: 11, note: '' },
  '黑莓': { min: 9, max: 11, note: '' }
}

// 水果出汁率和糖度数据
const fruitYieldData = {
  '苹果': { yieldFactor: 0.65, brixRange: '12-14', note: '品种差异' },
  '葡萄': { yieldFactor: 0.70, brixRange: '16-18', note: '品种重要' },
  '草莓': { yieldFactor: 0.85, brixRange: '8-11', note: '季节影响' },
  '樱桃': { yieldFactor: 0.75, brixRange: '14-16', note: '甜度高' },
  '桃子': { yieldFactor: 0.60, brixRange: '8-12', note: '成熟度影响' },
  '李子': { yieldFactor: 0.65, brixRange: '12-15', note: '品种差异大' },
  '橙子': { yieldFactor: 0.50, brixRange: '11-13', note: '成熟度影响' },
  '西瓜': { yieldFactor: 0.80, brixRange: '8-10', note: '熟透更甜' },
  '蓝莓': { yieldFactor: 0.75, brixRange: '10-12', note: '' },
  '树莓': { yieldFactor: 0.80, brixRange: '9-11', note: '' }
}

const fruitOptions = Object.entries(fruitYieldData).map(([key, data]) => ({
  value: key,
  label: `${data.name} (${data.brixRange}°Bx)`
}))

// 响应式状态
const selectedFruit = ref('')
const fruitWeight = ref('')
const weightUnit = ref('g')
const volumeUnit = ref('mL')
const originalBrix = ref('')
const targetBrix = ref('')
const juiceVolume = ref('')
const measurementTemp = ref('20.0')

// Weight conversion factors
const weightFactors = {
  g: 1,
  kg: 1000,
  lb: 453.592
}

// Computed properties for fruit data
const selectedFruitData = computed(() => {
  return selectedFruit.value ? fruitYieldData[selectedFruit.value] : null
})

const suggestedOriginalBrix = computed(() => {
  if (!selectedFruitData.value) return null
  const [min, max] = selectedFruitData.value.brixRange.split('-').map(Number)
  return (min + max) / 2
})

const brixRange = computed(() => {
  if (!selectedFruitData.value) return null
  const [min, max] = selectedFruitData.value.brixRange.split('-').map(Number)
  return { min, max }
})

// Weight and volume calculations
const weightInGrams = computed(() => {
  return fruitWeight.value * weightFactors[weightUnit.value]
})

const estimatedJuiceVolume = computed(() => {
  if (!selectedFruit.value || !weightInGrams.value) return 0
  
  const juiceVolumeInMl = weightInGrams.value * selectedFruitData.value.yieldFactor
  
  return volumeUnit.value === 'L' ? juiceVolumeInMl / 1000 : juiceVolumeInMl
})

// Watch for changes to update juice volume
watch([selectedFruit, fruitWeight], () => {
  if (estimatedJuiceVolume.value > 0) {
    juiceVolume.value = Math.round(estimatedJuiceVolume.value)
  }
})

// Watch for fruit selection to suggest Brix value
watch(selectedFruit, () => {
  if (suggestedOriginalBrix.value && !originalBrix.value) {
    originalBrix.value = suggestedOriginalBrix.value
  }
})

// 单位转换系数
const unitConversion = {
  'ml': 1,
  'l': 1000,
  'gal': 3785.41,
  'g': 1,
  'kg': 1000,
  'lb': 453.592
}

// 设置选中水果的糖度和更新出汁量
function setFruitBrix() {
  if (selectedFruit.value && fruitBrixData[selectedFruit.value]) {
    const fruit = fruitBrixData[selectedFruit.value]
    originalBrix.value = ((fruit.max + fruit.min) / 2).toString()
    if (fruitWeight.value) {
      juiceVolume.value = estimatedJuiceVolume.value
    }
    calculateDilution()
  }
}

// 转换体积单位
function convertVolume() {
  if (juiceVolume.value) {
    const ml = parseFloat(juiceVolume.value) * unitConversion[volumeUnit.value]
    juiceVolume.value = (ml / unitConversion[volumeUnit.value]).toFixed(2)
  }
}

// 温度校正
function temperatureCorrection(brix, temp) {
  // 基于标准温度20°C的校正公式
  const tempDiff = temp - 20
  return brix + (tempDiff * 0.06)
}

// 计算密度
function calculateDensity(brix) {
  // 基于糖度的密度近似计算公式
  return 1 + (brix * 0.004)
}

// 计算温度校正后的糖度
const tempCorrectedBrix = computed(() => {
  if (!originalBrix.value || !measurementTemp.value) return '0'
  const brix = parseFloat(originalBrix.value)
  const temp = parseFloat(measurementTemp.value)
  if (isNaN(brix) || isNaN(temp)) return '0'
  
  return temperatureCorrection(brix, temp).toFixed(1)
})

// 计算密度
const density = computed(() => {
  if (!targetBrix.value) return '1.000'
  const brix = parseFloat(targetBrix.value)
  if (isNaN(brix)) return '1.000'
  
  return calculateDensity(brix).toFixed(3)
})

// 计算所需水量
const waterToAdd = computed(() => {
  if (!originalBrix.value || !targetBrix.value || !juiceVolume.value) return 0
  if (Number(targetBrix.value) >= Number(originalBrix.value)) return 0
  
  const volumeInMl = volumeUnit.value === 'L' ? juiceVolume.value * 1000 : juiceVolume.value
  const dilutionFactor = (Number(originalBrix.value) / Number(targetBrix.value)) - 1
  const waterVolumeInMl = volumeInMl * dilutionFactor
  
  return volumeUnit.value === 'L' ? waterVolumeInMl / 1000 : waterVolumeInMl
})

// 计算总体积
const totalVolume = computed(() => {
  if (!waterToAdd.value || !juiceVolume.value) return 0
  return Number(juiceVolume.value) + waterToAdd.value
})

// 计算稀释比例
const dilutionRatio = computed(() => {
  if (!waterToAdd.value || !juiceVolume.value) return 0
  return (waterToAdd.value / Number(juiceVolume.value)).toFixed(2)
})

// 计算糖分含量
const sugarContent = computed(() => {
  if (!targetBrix.value) return 0
  // 每度Brix约等于10g/L的糖含量
  return Number(targetBrix.value) * 10
})

// 计算函数
function calculateDilution() {
  if (!originalBrix.value || !targetBrix.value || !juiceVolume.value ||
      isNaN(originalBrix.value) || isNaN(targetBrix.value) || isNaN(juiceVolume.value)) {
    return
  }

  const ob = parseFloat(originalBrix.value)
  const tb = parseFloat(targetBrix.value)
  const vol = parseFloat(juiceVolume.value) * unitConversion[volumeUnit.value]

  // 范围验证
  if (ob <= 0 || ob > 80 || 
      tb <= 0 || tb >= ob ||
      vol <= 0 || vol > 1000000) {
    return
  }
}

// 监听输入变化
watch(
  [originalBrix, targetBrix, juiceVolume, measurementTemp, volumeUnit, fruitWeight, weightUnit],
  calculateDilution
)

// Additional computed properties
const canCalculate = computed(() => {
  return originalBrix.value && 
         targetBrix.value && 
         juiceVolume.value && 
         Number(targetBrix.value) < Number(originalBrix.value)
})
</script>

<style scoped>
.dilution-calculator {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.input-section {
  margin: 20px 0;
  display: grid;
  gap: 15px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.input-with-unit {
  display: flex;
  gap: 10px;
}

.input-with-unit input {
  flex: 1;
}

input[type="number"],
select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

/* 移除数字输入框的上下箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.results-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.fruit-info,
.calculation-results {
  display: grid;
  gap: 10px;
}

.reference-section {
  margin-top: 30px;
}

.fruit-reference-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.fruit-reference-item {
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: 10px;
  align-items: center;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.fruit-name {
  font-weight: 500;
}

.fruit-brix {
  color: #666;
}

.fruit-yield {
  color: #2c3e50;
}
</style> 